<template>
  <div v-cloak id="main">
    <!--配置项-->
    <h4 class="weui-header-title" style="position: relative; background-color: #333;color: #FFFFFF; text-align: center; height: 40px;line-height: 40px">
      <span class="arrow"></span>
      <span style="position: absolute;left: 20px;top: 0;" @click="reTurnList()">公众号列表</span>
      <img @click="loginOut()" style="position: absolute;right: 10px;top: 50%;margin-top: -15px;cursor: pointer;" width="30" src="static/out.png" alt="">
      </h4>
    <div class="page__bd clearfix" style="position: absolute;left: 0;top: 40px">
      <div class="weui-cells" style="margin-top: 0">
        <div class="weui-cell weui-cell_select weui-cell_select-before" style="padding-right: 0">
          <div class="weui-cell__hd">
            <select class="weui-select" v-model="$root.IPConfig.http" style="width: 75px;font-size: 13px;padding: 0 0 0 10px">
              <option value="http://">http://</option>
              <option value="https://">https://</option>
            </select>
          </div>
          <div class="weui-cell__bd" style="display: flex;font-size: 15px">
            <input type="text" style="width: 150px;"  v-model="$root.IPConfig.HOST" class="weui-input" placeholder="HOST">:
            <input type="text" style="text-align: center;" v-model="$root.IPConfig.PORT" class="weui-input" placeholder="PORT">
          </div>
          <div class="weui-btn weui-btn_primary" style="font-size: 13px;padding: 0 10px;margin-right: 5px" @click="reCode()">刷新code</div>
        </div>
      </div>
    </div>
    <!--页面主体-->
    <div id="container">
      <div id="scroll">
        <div :class="info.hasRight?'msg-list clearfix rightStyle':'msg-list clearfix'" v-for="(info, index) in $root.infoList" @click="infoClick(info)">
          <div class="head"><img :src="info.mpName?'static/customer.jpg':'static/cat.ico'"></div>
          <div class="name">{{info.mpName?info.mpName:mpName}}</div>
          <div class="text" :style="info.mpName?'':'background-color:#fff'" style="white-space: normal;word-wrap: break-word;word-break: break-all;-webkit-user-select: text;-moz-user-select: text;-ms-user-select: text;user-select: text;" v-html="info.eventName === 'CodeCreatedEvent'?'微信code：'+info.code:info.content"></div>
          <div class="arrow" :style="info.mpName?'':'border-right-color:#fff'"></div>
        </div>
      </div>

    </div>
    <!--底部板块-->
    <div style="height: 627px;">
      <!--input面板-->
      <div id="footer-chat-bar-input" style="width: 375px;position: absolute;bottom: 0;left: 50%;margin-left: -187.5px" class="clearfix">
        <div class="chat-bar-left category-icon">
          <i class="icon-bar iconfont icon-category-up"></i>
        </div>
        <div class="chat-bar-right">
          <div class="chat-input"><input type="text" @keyup.enter="sendMessage()" class="chat-input-item" v-model="content" placeholder="输入内容..." /></div>
        </div>
      </div>
      <!--导航面板-->
      <div id="footer-chat-bar-target" style="width: 375px;position: absolute;bottom: 0;left: 50%;margin-left: -187.5px" class="clearfix">
        <div class="chat-bar-left keyboard-icon">
          <i class="icon-bar iconfont icon-keyboard-down"></i>
        </div>
        <div class="chat-bar-right">
          <div class="chat-bar-item parent-bar" v-for="muse in museList" @click="menuClick(muse)">
            <i v-if="muse.subButtons" class="icon-n-bar iconfont icon-daohang"></i>&nbsp;{{muse.name}}
            <section v-if="muse.subButtons">
              <div class="bar-t"></div>
              <div class="bar-s"></div>
              <div class="chat-bar-child-list">
                <div v-for="submuse in muse.subButtons" @click.stop="childMenuClick(submuse)"
                     class="chat-bar-child-item">{{submuse.name}}
                </div>
              </div>
            </section>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    data: function () {
      return {
        museList: [],
        mpName: '',
        content: ''
      }
    },
    mounted() {
      $('#main').animateCss('bounceInRight', function() {
        // Do somthing after animation
      });
      //二级导航菜单
      var footerChatBarTarget = new Hammer($("#footer-chat-bar-target")[0]);
      footerChatBarTarget.on('tap', function (ev) {
        if ($(ev.target).hasClass("chat-bar-item")) {
          $(".chat-bar-child-list,.bar-t,.bar-s").slideUp(200);
        }
        if ($(ev.target).hasClass("parent-bar") && !$(ev.target).find(".chat-bar-child-list").is(":animated")) {
          $(ev.target).find(".chat-bar-child-list,.bar-t,.bar-s").slideToggle(200);
        }
      });

      //底部导航菜单切换
      var categoryIcon = new Hammer($(".category-icon")[0]);
      categoryIcon.on('tap',function(ev){
        $(".jianpan-icon").hide();
        $(".face-icon").show();

        if($("#footer-chat-more").height()>0 || $("#footer-chat-face").height()>0){
          $("#footer-chat-more,#footer-chat-face").height(0);
          $("#footer-chat-bar-input,#footer-chat-bar-target").animate({"bottom":"0"},200);
        }
        $("#footer-chat-bar-input").animate({"height":"0"},200).hide();
        $("#footer-chat-bar-target").show().animate({"height":"48"},200);
      });
      var keyboardIcon = new Hammer($(".keyboard-icon")[0]);
      keyboardIcon.on('tap',function(ev){
        $(".chat-bar-child-list,.bar-t,.bar-s").slideUp(200);
        $("#footer-chat-bar-target").animate({"height":"0"},200).hide();
        $("#footer-chat-bar-input").show().animate({"height":"48"},200);
      });
      new Hammer($("#container")[0]).on("tap", function (ev) {
        $("#footer-chat-face,#footer-chat-more").height(0);
        $(".chat-bar-child-list,.bar-t,.bar-s").slideUp(200);
      });

      //底部键盘
      var keyboardIcon = new Hammer($(".keyboard-icon")[0]);
      keyboardIcon.on('tap',function(ev){
        $(".chat-bar-child-list,.bar-t,.bar-s").slideUp(200);
        $("#footer-chat-bar-target").animate({"height":"0"},200).hide();
        $("#footer-chat-bar-input").show().animate({"height":"48"},200);
      });
    },
    created: function () {
      let that = this;
      Vue.ws.onmessage = function (e) {
        let data =JSON.parse(e.data);

        if(data.mpId !== JSON.parse(localStorage.getItem('selectItem')).mpId) {
          weui.topTips(`刷新code失败，请到"${JSON.parse(localStorage.getItem('selectItem')).mpName}"公众号点击链接刷新code`,{
            className: 'topTipsStype',
            // duration: 1000000
          });
          return;
        }


        if(data.content) {
          data.content = data.content.replace(/\n/g,'<br/>');

          that.$root.infoList.push(data);

          Vue.nextTick(function () {
            if(document.getElementById("scroll").clientHeight > document.getElementById("container").clientHeight) {
              $('#container').scrollTop(document.getElementById("scroll").clientHeight-document.getElementById("container").clientHeight+1000)
            }
          });
        }
        if(data.code) {
          let infoList = [];
          localStorage.setItem('code', data.code);
          localStorage.setItem('openId', data.openId);
          infoList.push(data);
          localStorage.setItem('infoList', JSON.stringify(infoList));
          that.$root.infoList.push(data);
          Vue.nextTick(function () {
            if(document.getElementById("scroll").clientHeight > document.getElementById("container").clientHeight) {
              $('#container').scrollTop(document.getElementById("scroll").clientHeight-document.getElementById("container").clientHeight+1000)
            }
          });
        }
      };
      this.museList = JSON.parse(localStorage.getItem("museList"));
      if(this.$root.infoList.length === 0) {
        this.$root.infoList.push({
          content: 'mpId：'+JSON.parse(localStorage.getItem("infoList"))[0].mpId+'</br>openId：'+JSON.parse(localStorage.getItem("infoList"))[0].openId
        });
        this.$root.infoList.push(JSON.parse(localStorage.getItem("infoList"))[0]);
      }
      this.mpName = JSON.parse(localStorage.getItem("selectItem")).mpName;
    },
    methods: {
      reCode: function() {
        this.axios.post('wx_gateway/debugging/v1/codes').then((res) => {
          this.$root.infoList.push({
            eventName: "CodeCreatedEvent",
            code: '微信code已刷新，请点击手机调试信息'
          });
          Vue.nextTick(function () {
            if(document.getElementById("scroll").clientHeight > document.getElementById("container").clientHeight) {
              $('#container').scrollTop(document.getElementById("scroll").clientHeight-document.getElementById("container").clientHeight+1000)
            }
          });
        }).catch(() =>{
          weui.topTips('sorry!请求错误',{
            className: 'topTipsStype'
          })
        })
      },
      childMenuClick: function (item) {
        $(".chat-bar-child-list,.bar-t,.bar-s").slideUp(200);
        this.urlFormat(item)
      },
      menuClick: function (item) {
        if (item.url) {
          this.urlFormat(item)
        }
      },
      infoClick: function (info) {
        if(info.eventName === "TemplateSentEvent") {
          this.urlFormat(info)
        }
      },
      urlFormat: function (item) {
        if(item.url.indexOf('http://') === 0 || item.url.indexOf('https://') === 0) {
          this.$root.infoUrl = item.url;
          this.$router.push('/info');
          return;
        }
        if (item.url.includes('?') && item.url.includes('#')) {
          this.$root.infoUrl = this.$root.IPConfig.http + this.$root.IPConfig.HOST + ':' + this.$root.IPConfig.PORT + item.url.replace('#', '&code=' + localStorage.getItem('code') + '#');
          this.$router.push('/info');
          return;
        }
        if (item.url.includes('?')) {
          this.$root.infoUrl = this.$root.IPConfig.http + this.$root.IPConfig.HOST + ':' + this.$root.IPConfig.PORT + item.url + '&code=' + localStorage.getItem('code');
          this.$router.push('/info');
          return;
        }
        if (item.url.includes('#')) {
          this.$root.infoUrl = this.$root.IPConfig.http + this.$root.IPConfig.HOST + ':' + this.$root.IPConfig.PORT + item.url.replace('#', '?code=' + localStorage.getItem('code') + '#');
          this.$router.push('/info');
          return;
        }
        this.$root.infoUrl = this.$root.IPConfig.http + this.$root.IPConfig.HOST + ':' + this.$root.IPConfig.PORT + item.url + '?code=' + localStorage.getItem('code');
        this.$router.push('/info');
      },
      reTurnList() {
        this.$root.infoList = [];
        this.$router.push('/list')
      },
      sendMessage: function () {
        if(this.content === '') {
          weui.topTips('请输入内容',{
            className: 'topTipsStype'
          });
          return;
        }
        this.resetInfo(true,this.content,localStorage.getItem('username'));
        this.axios.post('wx_gateway/debugging/v1/msg_receiving',{content:this.content}).then((res) =>{
          if(res.data.data) {
            this.resetInfo(false,res.data.data)
          }
          this.content = '';
        }).catch((err) =>{
          this.content = '';
          weui.topTips(err.response.data.errorMessage,{
            className: 'topTipsStype'
          })
        });
      },
      loginOut: function() {
        // 清除全部存储、断开websocket
        localStorage.clear();
        Vue.ws.close();
        Vue.ws = undefined;
        this.$root.infoList = [];
        this.$router.push('/login');
      },
      //更新message
      resetInfo: function (hasRight,content,mpName) {
        this.$root.infoList.push({
          hasRight: hasRight,
          mpName: mpName,
          content: content
        });
        Vue.nextTick(function () {
          if(document.getElementById("scroll").clientHeight > document.getElementById("container").clientHeight) {
            $('#container').scrollTop(document.getElementById("scroll").clientHeight-document.getElementById("container").clientHeight+1000)
          }
        });
      }

    }
  }
</script>
<style>
  [v-cloak] {
    display: none;
  }

  #container {
    height: 529px;
    margin-top: 90px;
  }
  .arrow{
    content: " ";
    display: inline-block;
    height: 6px;
    width: 6px;
    border-width: 2px 2px 0 0;
    border-color: #FFFFFF;
    border-style: solid;
    -webkit-transform: matrix(-0.71, -0.71, 0.71, -0.71, 0, 0);
    transform: matrix(-0.71, -0.71, 0.71, -0.71, 0, 0);
    position: absolute;
    top: 50%;
    margin-top: -4px;
    left: 10px;
  }
  .rightStyle .head {
    position: absolute;
    top: 0px;
    left: auto;
    right: 0px;
    width: 45px;
    height: 45px;
    display: block;
    overflow: hidden;
  }
  .rightStyle .name {
    left: auto;
    right: 60px;
  }
  .rightStyle .arrow {
    position: absolute;
    content: " ";
    width: 0;
    height: 0;
    top: 27px;
    left: auto;
    right: 48px;
    border-top: 8px solid transparent;
    border-bottom: 8px solid transparent;
    border-right: 14px solid #B3E866;
    z-index: -1;
    margin-top: -10px;
    transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
  }
  .rightStyle .text {
    float: right;
  }
</style>
